package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ThresholdConfigServlet", value = "/ThresholdConfigServlet")
public class ThresholdConfigServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String DB_USER = "webdb";
    private static final String DB_PASSWORD = "webdb";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 查询所有阈值配置
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM threshold_config")) {

            StringBuilder json = new StringBuilder("[");
            while (rs.next()) {
                if (json.length() > 1) json.append(",");
                json.append("{")
                        .append("\"id\":").append(rs.getInt("id")).append(",")
                        .append("\"paramType\":\"").append(rs.getString("param_type")).append("\",")
                        .append("\"thresholdValue\":").append(rs.getDouble("threshold_value")).append(",")
                        .append("\"unit\":\"").append(rs.getString("unit")).append("\"")
                        .append("}");
            }
            json.append("]");
            out.println(json.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("{\"error\": \"查询失败: " + e.getMessage() + "\"}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 处理管理人员更新阈值配置
        try (Connection conn = getConnection()) {
            // 读取JSON请求体
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String jsonStr = buffer.toString();

            // 解析JSON数组
            String[] updates = jsonStr.substring(1, jsonStr.length() - 1).split("\\},\\{");
            conn.setAutoCommit(false);

            try {
                for (String update : updates) {
                    // 简单解析JSON对象
                    update = update.replaceAll("[{}\"]", "");
                    String[] pairs = update.split(",");
                    String paramType = null;
                    double thresholdValue = 0;

                    for (String pair : pairs) {
                        String[] keyValue = pair.split(":");
                        if (keyValue[0].trim().equals("paramType")) {
                            paramType = keyValue[1].trim();
                        } else if (keyValue[0].trim().equals("thresholdValue")) {
                            thresholdValue = Double.parseDouble(keyValue[1].trim());
                        }
                    }

                    if (paramType != null) {
                        // 更新阈值
                        try (PreparedStatement pstmt = conn.prepareStatement(
                                "UPDATE threshold_config SET threshold_value = ?, update_time = NOW() WHERE param_type = ?")) {

                            pstmt.setDouble(1, thresholdValue);
                            pstmt.setString(2, paramType);
                            pstmt.executeUpdate();
                        }
                    }
                }

                conn.commit();
                out.println("{\"success\": true}");
            } catch (Exception e) {
                conn.rollback();
                throw e;
            } finally {
                conn.setAutoCommit(true);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            out.println("{\"error\": \"更新失败: " + e.getMessage() + "\"}");
        }
    }

    // 数据库连接
    private Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new SQLException("JDBC驱动加载失败", e);
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }
}